<?php

namespace App\Http\Services;

use App\Http\Helpers\Sign;
use App\Models\Faces;

class FaceService{

    const APPKEY = "11F7AB57AB3E32D4";
    const APPSECRET = "ACB5C12C15B4525C3643E728DC8EF120";

    /**
     *人脸列表
     * @author: lican<364548233@qq.com>
     */
    public static function list($keyword, $page, $pageSize){
        $face = Faces::select('id', 'card_number', 'face');
        if($keyword){
            $face->where('card_number', 'like', "%{$keyword}%");
        }
        $total = $face->count();
        $list = $face->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
        foreach($list as $k => $v){
            $i = ltrim($v['face'], '.');
            $list[$k]['face'] = DOMAIN . $i;
        }
        return MsgService::getMsg(0, ['total' => $total, 'list' => $list]);
    }

    /**
     *参数校验
     * @author lican<364548233@qq.com>
     */
    public static function handle($data){
        if(empty($data) || !isset($data['appKey'])){
            return MsgService::getMsg(1009);
        }
        if($data['appKey'] != self::APPKEY){
            return MsgService::getMsg(1008);
        }
        $sign = Sign::colsign($data, self::APPSECRET);
        if($data['signature'] != $sign){
            Sign::writeLog('签名验证：', '验证失败！', 'face');
            return MsgService::getMsg(1005);
        }
        Sign::writeLog('签名验证：', '验证成功！', 'face');
        $push = [
            "card_number" => $data['cardNumber'],
            "school_code" => $data['schoolCode'],
            "image_url" => $data['imageUrl'],
            "nonce" => $data['nonce'],
            "signature" => $data['signature']
        ];
        $base64ImageContent = self::imgBase64Encode($data['imageUrl']) ?: '';
        $facePath = self::imgBase64Decode($base64ImageContent, true, '../public/uploads/images/face/');
        Sign::writeLog('保存本地：', $facePath, 'face');
        $push['face'] = $facePath;
        $res = self::add($push);
        if($res){
            Sign::writeLog('人脸推送状态：', '推送成功_id：'.$res->id, 'face');
            return json_encode(['result' => 1,' msg' => 'ok']);
        }else{
            Sign::writeLog('人脸推送状态：', '推送失败：存库失败', 'face');
            return MsgService::getMsg(-1);
        }

    }

    /**
     *人脸参数保存
     * @author lican<364548233@qq.com>
     */
    public static function add($data){
        $face = Faces::where('school_code', $data['school_code'])
            ->where('card_number', $data['card_number'])
            ->first();
        if(!$face){
            $face = new Faces();
        }
        $face->school_code = $data['school_code'];
        $face->card_number = $data['card_number'];
        $face->nonce = $data['nonce'];
        $face->image_url = $data['image_url'];
        $face->face = $data['face'];
        $face->save();
        return $face;
    }

    /**
     * 图片base64encode
     * @param string $img
     * @param bool $imgHtmlCode
     * @return string
     */
    public static function imgBase64Encode($img = '', $imgHtmlCode = true)
    {
        //如果是本地文件
        if (strpos($img, 'http') === false && !file_exists($img)) {
            return $img;
        }
        //获取文件内容
        $file_content = file_get_contents($img);
        if ($file_content === false) {
            return $img;
        }
        $imageInfo = getimagesize($img);
        $prefiex = '';
        if ($imgHtmlCode) {
            $prefiex = 'data:' . $imageInfo['mime'] . ';base64,';
        }
        $base64 = $prefiex . chunk_split(base64_encode($file_content));
        return $base64;
    }

    /**
     * 图片base64解码
     * @param string $base64_image_content
     * @param bool $save_img
     * @param string $path
     * @return bool|string
     */
    public static function imgBase64Decode($base64_image_content = '', $save_img = false, $path = '')
    {
        if (empty($base64_image_content)) {
            return false;
        }

        //匹配出图片的信息
        $match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result);
        if (!$match) {
            return false;
        }

        //解码图片内容(方法一)
        /*$base64_image = preg_split("/(,|;)/",$base64_image_content);
        $file_content = base64_decode($base64_image[2]);
        $file_type = substr(strrchr($base64_image[0],'/'),1);*/

        //解码图片内容(方法二)
        $base64_image = str_replace($result[1], '', $base64_image_content);
        $file_content = base64_decode($base64_image);
        $file_type = $result[2];

        //如果不保存文件,直接返回图片内容
        if (!$save_img) {
            return $file_content;
        }

        //如果没指定目录,则保存在当前目录下
        if (empty($path)) {
            $path = __DIR__;
        }
        $file_path = $path . "/" . date('Ymd', time()) . "/";
        if (!is_dir($file_path)) {
            //检查是否有该文件夹，如果没有就创建
            mkdir($file_path, 0777, true);
        }
        $file_name = time().str_random(8) . ".{$file_type}";
        $new_file = $file_path . $file_name;
        if (file_exists($new_file)) {
            //有同名文件删除
            @unlink($new_file);
        }
        if (file_put_contents($new_file, $file_content)) {
            return $new_file;
        }
        return false;
    }

}
